import React, { Component } from 'react'
import queryString from 'query-string'
import moment from 'moment'
import { withRouter, Link } from 'react-router-dom'
import styles from './style.module.scss'
import ContentSideNav from '../../components/common/ContentSideNav'
import Page from '../../components/common/Page'
import DropSelector from '../../components/DropSelector'
import ask from '../../serve/api';

const contentSideNavList = [{
  title : '资讯库',
  id : 'news',
},{
  title : '专题库',
  id : 'course'
},{
  title : '联盟库',
  id : 'orgJg',
},{
  title : '专家库',
  id : 'professor',
},{
  title : '成果库',
  id : 'result',
},{
  title : '视频库',
  id : 'media'
}];

export default withRouter(class ThinkTankData extends Component {

  constructor(props){
    super();
    this.state = {
      contentSideNavList : [],
      loadState : 'pengding',
      contentList : [],
      totalPage : 0,
      contentPage : 1,
      contentPageSize : 10,
      typeId : undefined,
      typeCategoryIndex : null,
      typeCategoryArray : [],
      subject : {
        inputVal : '',
      },
      media : {
        inputVal : '',
      },
      professorData : {
        inputVal : '',
        searchTypes : {
          index : 0,
          list : [{
            name : '专家姓名',
            code : 0,
          },{
            name : '研究领域',
            code : 1,
          },{
            name : '所在部门',
            code : 2,
          }]
        },
        letterIndex: null,
        letterList : ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],
      },
    }
  }

  componentDidMount() {
    // 获取类型列表
    this.setState({contentSideNavList},()=>{
      // 设置nav id
      this.setTypeId(()=>{
        // 获取列表
        this.setListData();
      });
    });
  }

  componentDidUpdate(prevProps, prevState) {
    if(this.props.location !== prevProps.location){
      // 设置nav id
      this.setTypeId(()=>{
        // 获取列表
        this.setListData();
      });
      
    };
  }

  setTypeId = (callback)=>{
    const {location} = this.props;
    const oSearch = queryString.parse(location.search);
    const typeId = oSearch.id? oSearch.id : this.state.contentSideNavList[0]? this.state.contentSideNavList[0].id : undefined;
    this.setState({
      typeId,
    }, callback);
  }

  setListData = ()=>{
    const {professorData, typeCategoryArray, typeCategoryIndex, subject, media} = this.state;
    const typeCategoryId = typeCategoryArray[typeCategoryIndex]? typeCategoryArray[typeCategoryIndex].id : undefined;
    // 获取列表
    switch(this.state.typeId){
      case 'course' : 
        this.fetchItemList({api : 'fetchListCourse', params : {
          searchKey : subject.inputVal || undefined,
        } });
      break;
      case 'media' : 
        this.fetchItemList({api : 'fetchListMedia', params : {
          searchKey : media.inputVal || undefined,
        } });
      ;break;
      case 'news' : 
        this.fetchTypeAllCategory({api : 'fetchListHotNewsTypeAll'}).then(()=>{
          this.fetchItemList({api : 'fetchListHotNews', params : {
            typeId : typeCategoryId,
            // searchKey : this.state.typeCategoryArray,
          } });
        });
      break;
      case 'professor' : 
        this.fetchItemList({api : 'fetchListProfessor', params : {
          pageSize : 99999,
          typeId : professorData.searchTypes.list[professorData.searchTypes.index].code,
          searchKey : professorData.inputVal.trim()? professorData.inputVal.trim() : undefined,
        } }, ({result, resultNum})=>{
          const contentList = Array.isArray(result)? result:[];
          this.setState({
            loadState : 'success',
            contentList,
            totalPage : 0,
          });
        });
        
      break;
      case 'orgJg' : this.fetchItemList({api : 'listOrg'});
      break;
      case 'result' : 
        this.fetchItemList({api : 'fetchListTtResult'});
      break;
      default : 
        this.setState({
          loadState : 'success',
          contentList : [],
          totalPage : 0,
        });
      
    };
    
    
  }

  async fetchTypeAllCategory ({api}){
    if(!api){
      this.setState({
        typeCategoryArray : [],
      });
      return;
    };
    const {code, result} = await ask[api]();
    try {
      if(code !== '000000'){
        throw new Error('数据出错');
      };
      this.setState({
        typeCategoryArray : result
      });
    } catch (error) {
      console.log(error);
      this.setState({
        typeCategoryArray : [],
        totalPage : 0,
      });
    }
  }

  async fetchItemList ({api, params}, setData){
    this.setState({
      contentList : [],
      loadState : 'pengding',
    });
    const {contentPageSize, contentPage} = this.state;
    // 获取列表
    let new_params = Object.assign({}, {
      page : contentPage,
      pageSize : contentPageSize,
    }, params);
    if(!api){
      this.setState({
        contentList : [],
        totalPage : 0,
      });
      return;
    };
    const {code, result, resultNum} = await ask[api](new_params);
    try {
      if(code !== '000000'){
        throw new Error('数据出错');
      };

      if(typeof setData === 'function'){
        setData({code, result, resultNum});
      }else{
        const contentList = Array.isArray(result)? result:[];
        const totalPage = resultNum || 0;
        this.setState({
          contentList,
          totalPage,
          loadState : 'success',
        });
      };
    } catch (error) {
      console.log(error);
      this.setState({
        contentList : [],
        totalPage : 0,
        loadState : 'error',
      });
    }
  }

  renderContent = ()=>{
    let component;
    switch(this.state.typeId){
      case 'course' : component = this.Subject();break;
      case 'media' : component = this.Media();break;
      case 'news' : component = this.News();break;
      case 'professor' : component = this.ProfessorList();break;
      case 'orgJg' : component = this.orgJg();break;
      case 'result' : component = this.Result();break;
      default : component = '';
    };

    return component;
  }

  // 通用列表
  orgJg = ()=>{
    const {contentList} = this.state;
    return (
      <ul className={styles.commonlist}>
        { contentList.map((item, index)=> {
          const title = item.title || item.name;
          return <li key={index}><Link title={title} to={`/org/main?orgId=${item.id}`} >{title}</Link><span className={styles.date}>{moment(item.public_at).format('YYYY-MM-DD')}</span></li>;
        } ) }
      </ul>
    );
  }

  Result = ()=>{
    const {contentList} = this.state;
    return (
      <ul className={styles.commonlist}>
        { contentList.map((item, index)=> {
          const title = item.title || item.name;
          return <li key={index}><Link title={title} to={`/mainPage/pageDetail/result/${item.id}`} >{title}</Link><span className={styles.date}>{moment(item.public_at).format('YYYY-MM-DD')}</span></li>;
        } ) }
      </ul>
    );
  }

  onDropSelectorItemClick = ({item, index})=>{
    this.setState({
      typeCategoryIndex : index
    });
  }

  onNewsSearch = ()=>{
    const {typeCategoryArray, typeCategoryIndex} = this.state;
    const typeCategoryId = typeCategoryArray[typeCategoryIndex]? typeCategoryArray[typeCategoryIndex].id : undefined;
    this.fetchItemList({api : 'fetchListHotNews', params : {
      typeId : typeCategoryId,
    } });
  }

  // 专题库
  Subject = ()=>{
    const {contentList, subject} = this.state;
    return (
      <div className={styles.commonlistwrap}>
        <div className={styles.searchwrap}>
          <span className={styles.tit}><input className={styles.inp} type="text" placeholder="专题搜索" value={subject.inputVal}  onChange={ e => { this.onSubjectInputChange(e); }} /></span>
          <a className={styles.searchbtn} onClick={this.onSubjectSearch}>搜索</a>
        </div>
        <ul className={styles.commonlist}>
          { contentList.map((item, index)=> {
            const title = item.title || item.name;
            return <li key={index}><Link title={title} to={`/mainPage/pageDetail/course/${item.id}`} >{title}</Link><span className={styles.date}>{moment(item.public_at).format('YYYY-MM-DD')}</span></li>;
          } ) }
        </ul>
      </div>
    );
  }

  // 新闻资讯
  Media = ()=>{
    const {contentList, media} = this.state;
    return (
      <div className={styles.commonlistwrap}>
        <div className={styles.searchwrap}>
          <span className={styles.tit}><input className={styles.inp} type="text" placeholder="视频搜索" value={media.inputVal}  onChange={ e => { this.onMediaInputChange(e); }} /></span>
          <a className={styles.searchbtn} onClick={this.onMediaSearch}>搜索</a>
        </div>
        <ul className={styles.medialist}>
          { contentList.map((item, index)=> {
            const title = item.title || item.name;
            return (
              <li key={index}>
                <span className={styles.picwrap}>
                  <video src={item.url} width="100%" height="100%" controls="controls" >
                    your browser does not support the video tag
                  </video>
                </span>
                <div className={styles.conwrap}>
                  <h3><Link title={title} to={`/mainPage/pageDetail/media/${item.id}`} >{title}</Link></h3>
                  <div className={styles.con} dangerouslySetInnerHTML={{__html : item.content}}></div>
                </div>
              </li>
            )
          } ) }
        </ul>
      </div>
    );
  }

  onMediaInputChange = (e)=>{
    const {media} = this.state;
    media.inputVal = e.target.value;
    this.setState({
      media
    });
  }

  onMediaSearch = ()=>{
    const {media} = this.state;
    const searchKey = media.inputVal.trim() || undefined; 
    this.fetchItemList({api : 'fetchListMedia', params : {
      searchKey,
    } });
  }

  onSubjectInputChange = (e)=>{
    const {subject} = this.state;
    subject.inputVal = e.target.value;
    this.setState({
      subject
    });
  }

  onSubjectSearch = ()=>{
    const {subject} = this.state;
    const searchKey = subject.inputVal.trim() || undefined; 
    this.fetchItemList({api : 'fetchListCourse', params : {
      searchKey,
    } });
  }
  
  // 新闻资讯
  News = ()=>{
    const {contentList, typeCategoryArray, typeCategoryIndex} = this.state;
    return (
      <div className={styles.commonlistwrap}>
        <div className={styles.searchwrap}>
          <span className={styles.tit}>查询分类：
            <DropSelector defaultIndex={typeCategoryIndex} list={typeCategoryArray} onItemClick={this.onDropSelectorItemClick} />
          </span>
          <a className={styles.searchbtn} onClick={this.onNewsSearch}>搜索</a>
        </div>
        <ul className={styles.commonlist}>
          { contentList.map((item, index)=> {
            const title = item.title || item.name;
            return <li key={index}><Link title={title} to={`/mainPage/pageDetail/hotNews/${item.id}`} >{title}</Link><span className={styles.date}>{moment(item.public_at).format('YYYY-MM-DD')}</span></li>;
          } ) }
        </ul>
      </div>
    );
  }

  // 专家列表
  ProfessorList = ()=>{
    const {contentList, professorData} = this.state;
    const letterMap = [];
    professorData.letterList.forEach( letter => {
      contentList.map( item => {
        if( item.name_char && letter === item.name_char.toUpperCase() ){
          letterMap.push({
            id: item.id,
            name : item.name,
            name_char : item.name_char,
          });
        };
      } );
    } );

    const letterData = letterMap.filter(letter => professorData.letterIndex === null || professorData.letterList[professorData.letterIndex] === letter.name_char );
    return (
      <div className={styles.professorwrap}>
        <div className={styles.head}>
          <span className={styles.tit}>专家查询：<input className={styles.inp} type="text" placeholder="请输入关键字" defaultValue={professorData.inputVal}  onChange={ e => { this.onInputChange(e); }} /></span>
          <div className={styles.con}>
            <span className={styles.checkboxwrap}>
              {
                professorData.searchTypes.list.map( (type, index) => <a key={index} className={index === professorData.searchTypes.index? styles.on : ''} onClick={()=>{ this.onSearchTypeClick({type, index}); }}><em></em><i>{type.name}</i></a> )
              }
            </span>
            <a className={styles.searchbtn} onClick={this.searchProfessor}>搜索</a>
          </div>
        </div>
        <div className={styles.body}>
          <ul className={styles.letterList}>
            <li className={professorData.letterIndex === null? styles.on : ''} onClick={()=>{ this.onLetterTypeClick(null); }}><a>全部</a></li>
            { professorData.letterList.map((letter, index) => <li key={index} onClick={()=>{ this.onLetterTypeClick(index); }}><a style={professorData.letterIndex === index ? {color: '#e5371f'}: {color: '#242424'}}>{letter}</a></li>	) }
          </ul>
          <ul className={styles.letterItems}>
            { letterData.map( (item, index) => (
              <li key={index}><span>{item.name_char}</span><Link to={`/mainPage/professorDetail/thinkTankData/${item.id}`}>{item.name}</Link></li>
            ) ) }
          </ul>
        </div>
      </div>
    );
  }

  // 点击字母
  onLetterTypeClick = (index)=>{
    const {professorData} = this.state;
    professorData.letterIndex = index;
    this.setState({
      professorData
    });
  }

  onSearchTypeClick =({type, index})=>{
    const {professorData} = this.state;
    professorData.searchTypes.index =  index;
    this.setState({
      professorData
    });
  }
  
  // 专业智库 - 输入框事件
  onInputChange = (e)=>{
    const {professorData} = this.state;
    professorData.inputVal = e.target.value;
    this.setState({
      professorData
    });
  }
  
  searchProfessor = ()=>{
    this.setListData();
  }

  // 点击类型
  itemClick = ({item, index})=>{
    if(item.id === 'result'){
      const {history} = this.props;
      history.push('/mainPage/result');
      return;
    };
    this.changeRoute('id', item.id? item.id+'' : undefined);
    const {professorData} = this.state;
    professorData.inputVal = '';
    professorData.searchTypes.index = 0;
    professorData.letterIndex = null;
    // 重置分页
    this.setState({
      contentPage : 1,
      totalPage : 0,
      subject : {
        inputVal : ''
      },
      media : {
        inputVal : ''
      },
      professorData,
    });
  }

  changeRoute = (propname, value)=>{
    const {history, location} = this.props;
    let oSearch = queryString.parse(location.search);
    let methods;
    if(oSearch[propname] === value){
      methods = 'replace';
    }else{
      methods = 'push';
      value? oSearch[propname] = value : delete oSearch[propname];
    };
    const search = queryString.stringify(oSearch);
    history[methods]({search});
  }

  activeKey = (val)=>{
    let index = 0;
    for(let i=0;i<this.state.contentSideNavList.length;i++){
      if(this.state.contentSideNavList[i].id + '' === val){
        index = i;
        break;
      }
    };
    return index;
  }

  // 点击分页按钮
  clickPageIndex = (contentPage)=>{
    // if(contentPage === 1) return ;
    this.setState({
      contentPage,
    },()=>{
      // 获取列表
      this.setListData();
    });
  }
  
  render() {
    const {
      contentSideNavList,
      loadState,
      contentList,
      totalPage,
      typeId,
      contentPage,
    } = this.state;

    const activeKey = this.activeKey(typeId);


    return (
      <div className={styles.forum_wrap}>
        <div className={styles.sidebar}>
          <ContentSideNav activeKey={activeKey} list={contentSideNavList} onItemClick={this.itemClick} />
        </div>
        <div className={styles.mainwrap}>
          { this.renderContent() }
          { loadState === 'error' && <p className={styles.nodata}>加载失败，请重试</p> }
          { loadState === 'pending' && <p className={styles.nodata}>正在加载...</p> }
          { loadState === 'success' && !contentList.length && <p className={styles.nodata}>暂无相关数据</p> }
          { !!totalPage && <Page 
            pageConfig={{totalPage, currentPage : contentPage}}
            pageCallbackFn={this.clickPageIndex}
          />}
        </div>
      </div>
    )
  }
})
